<?php
/**
 * Created by PhpStorm.
 * User: Ruzi
 * Date: 2015/12/10
 * Time: 12:21
 */


header("Content-type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");


if(isset($_POST["url"])){

    $url=$_POST["url"];

        $hostinfo=@snmpwalk("$url","public","1.3.6.1.2.1.17.4.3.1.1");  // dot1dTpFdbAddress

    if(isset($hostinfo)&&!empty($hostinfo)) {
        $info=get_bridge($url,"public");
        $arr = array("success"=>true,"info" => $info);
        echo json_encode($arr);
    }else{
        $arr = array("success"=>false,"info" => "");
        echo json_encode($arr);

    }

}

if(isset($_GET["url"])){

    $url=$_GET["url"];

    $hostinfo=@snmpwalk("$url","public","1.3.6.1.2.1.17.4.3.1.1");  // dot1dTpFdbAddress

    if(isset($hostinfo)) {
        $info=get_bridge($url,"public");
        $arr = array("success"=>true,"info" => $info);
        echo json_encode($arr);
    }else{
        $arr = array("success"=>false,"info" => "");
        echo json_encode($arr);

    }

}



function get_bridge($host,$community){


    //mac地址
    $macaddr=@snmpwalk("$host","$community","1.3.6.1.2.1.17.4.3.1.1");  // dot1dTpFdbAddress
    //交换机物理端口
    $port=@snmpwalk("$host","$community","1.3.6.1.2.1.17.4.3.1.2");  // dot1dTpFdbPort
    //状态
    $stat=@snmpwalk("$host","$community","1.3.6.1.2.1.17.4.3.1.3");  // 	dot1dTpFdbStatus

    $tar1=array();
    $tar2=array();
    $tar3=array();


    $main_arr=array("mac"=>$tar1,"port"=>$tar1,"stat"=>$tar1);

    for ($i=0; $i <count($macaddr) ; $i++) {

        $ad=@trim(str_replace("Hex-STRING:","",$macaddr[$i]));
        $ad1=@strtolower(trim(str_replace(" ",":",$ad)));

        $po=@str_replace("INTEGER:","",$port[$i]);
        $st=@str_replace("INTEGER:","",$stat[$i]);

        $ad2=explode(":",$ad1);
        $newmac="";

        for($k=0;$k<count($ad2);$k++){

            $kad=$ad2[$k];
            if(strlen($kad)==1){
                $kad="0".$kad;
            }

            if($k==((count($ad2)-1))){
                $newmac=$newmac.$kad;
            }else{
                $newmac=$newmac.$kad.":";
            }

        }


        array_push($main_arr["mac"],trim($newmac));
        array_push($main_arr["port"],trim($po));
        array_push($main_arr["stat"],trim($st));

    }

    return $main_arr;

}